package com.xinxing.city.recovery;

import static com.xinxing.city.recovery.Constant.MSG_COLSE_CUT;
import static com.xinxing.city.recovery.Constant.MSG_COLSE_DOOR_WEIGHT;
import static com.xinxing.city.recovery.Constant.MSG_DELAYED_HK;
import static com.xinxing.city.recovery.Constant.MSG_HIDE_NOTIFY;
import static com.xinxing.city.recovery.Constant.MSG_HIDE_OVER;
import static com.xinxing.city.recovery.Constant.MSG_SEND_HEART;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.WriterException;
import com.scwang.wave.MultiWaveHeader;
import com.tbruyelle.rxpermissions3.Permission;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.xinxing.city.recovery.adapter.CategoryAdapter;
import com.xinxing.city.recovery.adapter.SimpleAdapter;
import com.xinxing.city.recovery.databinding.ActivityMainBinding;
import com.xinxing.city.recovery.entitys.BaseEntity;
import com.xinxing.city.recovery.entitys.BucketType;
import com.xinxing.city.recovery.entitys.Catalogs;
import com.xinxing.city.recovery.entitys.CleanOrder;
import com.xinxing.city.recovery.entitys.CleanQRCode;
import com.xinxing.city.recovery.entitys.KernelAction;
import com.xinxing.city.recovery.entitys.KernelActions;
import com.xinxing.city.recovery.entitys.LoginCheck;
import com.xinxing.city.recovery.entitys.MenuBean;
import com.xinxing.city.recovery.entitys.QRCodeClean;
import com.xinxing.city.recovery.entitys.QrMessage;
import com.xinxing.city.recovery.entitys.SetCategory;
import com.xinxing.city.recovery.entitys.SetWeightChange;
import com.xinxing.city.recovery.entitys.UpdataApk;
import com.xinxing.city.recovery.entitys.order;
import com.xinxing.city.recovery.interfaces.ICallBackWeight;
import com.xinxing.city.recovery.interfaces.IDeviceKernel;
import com.xinxing.city.recovery.interfaces.IOverFlowListener;
import com.xinxing.city.recovery.interfaces.IRfidManager;
import com.xinxing.city.recovery.interfaces.ISerialSendReceiveData;
import com.xinxing.city.recovery.interfaces.ITtsService;
import com.xinxing.city.recovery.net.BaseTask;
import com.xinxing.city.recovery.net.OkHttpRequest;
import com.xinxing.city.recovery.net.RetroFactory;
import com.xinxing.city.recovery.ui.CompOrderActivity;
import com.xinxing.city.recovery.ui.SetActivity;
import com.xinxing.city.recovery.utils.CheckUpdate;
import com.xinxing.city.recovery.utils.ErmCreate;
import com.xinxing.city.recovery.utils.GetWeight;
import com.xinxing.city.recovery.utils.LogWriter;
import com.xinxing.city.recovery.utils.MyDialog;
import com.xinxing.city.recovery.utils.SharedPreferencesUtils;

import com.xinxing.city.recovery.utils.SimplePreviewBig;
import com.xinxing.city.recovery.utils.VersionUtil;

import com.xinxing.city.recovery.utils.VideoSet;

import com.zhpan.bannerview.constants.PageStyle;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    LinearLayout _mainTanView; //主页
    private IDeviceKernel deviceKernel;
    private IRfidManager rfidManager;
    private ISerialSendReceiveData serialSendReceiveData;
    private ActivityMainBinding activityMainBinding;
    public static Gson gson; //json工具
    public int countDown = 30;//倒计时120秒
    //当前选中的menu
    private MenuBean menuBean;
    private CategoryAdapter categoryAdapter;
    private TextView countdownTextView; //倒计时文本
    private Boolean isTan = false;
    private CountDownTimer countDownTimer = null; //倒计时变量
    public static String loginCode; //登录Code
    public static String cleanCode = "";
    private List<BucketType> bucketTypes = new ArrayList<>();
    private ITtsService ttsService;
    private APPRuntime appRuntime;
    private SetBaseView baseView;
    private boolean jtSuccess = false;
    private GetWeight getWeight;
    private MyDialog mydialog = null;
    private SimplePreviewBig simplePreview;
    FrameLayout preview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        EventBus.getDefault().register(this);
        deviceKernel = DI.getInstance(IDeviceKernel.class);
        appRuntime = DI.getInstance(APPRuntime.class);
        deviceKernel.start(this);
        serialSendReceiveData = deviceKernel.getSerial();
        ttsService = deviceKernel.getTTS();
        ttsService.start(this);
        /*轮播图部分*/
        gson = new Gson();
        baseView = new SetBaseView(this);
        mHandler.sendEmptyMessageDelayed(MSG_SEND_HEART, 3000);
        mHandler.sendEmptyMessageDelayed(MSG_DELAYED_HK, 60000);

        getWeight = new GetWeight(this);
        categoryAdapter = new CategoryAdapter(R.layout.adapter_category, BR.bucket, this);
        activityMainBinding.recycler.setAdapter(categoryAdapter);
        preview = findViewById(R.id.simple_preview);
        bannerInit();
        initPermission();
        activityMainBinding.tvDiglog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        String test = String.format("%.1f0", 2.3650);
        Log.e("TTTh", test);
        //版本更新
//        PackageManager packageManager = getPackageManager();
//        PackageInfo packageInfo = null;
//        try {
//            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        String currentVersionCode = packageInfo.versionName;
//        updata(currentVersionCode);
//        ShellUtlis.execCmd("ip route add 192.168.1.0/24 via 192.168.1.20 dev eth1 table 1");
//        ShellUtlis.execCmd("ip rule add from all table 1 pref 1000");
//        mHandler.sendEmptyMessageDelayed(2, 2000);
        findViewById(R.id.touchuan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        findViewById(R.id.rly_Bw).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        findViewById(R.id.mainTanLogin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    private void updata(String version) {
        new BaseTask<UpdataApk>(this, RetroFactory.getJsonService().getUpdataApk("recycle-cabinet", "android", version)).handleResponse(new BaseTask.ResponseListener<UpdataApk>() {


            @Override
            public void onSuccess(UpdataApk updataApk) {
                VersionUtil versionUtils = new VersionUtil();
                int v = versionUtils.compareVersion(version, updataApk.getVersion());
                Log.e("TTT", "v " + v + "   version1 " + version + "  version2 " + updataApk.getVersion());
                if (v < 0) {
                    String parentFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download";
                    CheckUpdate checkUpdate = new CheckUpdate(MainActivity.this);
                    String url = Constant.BaseUrl + "/sr-asset/v1/assets?a=d&p=" + updataApk.getPkgPath();
                    checkUpdate.downNewApk(url, parentFile, "b.apk", CheckUpdate.DisplayMode.MODE_DIALOG_BOX);
                }
            }

            @Override
            public void onFail() {

            }
        });
    }

    private void initPermission() {
        RxPermissions rxPermission = new RxPermissions(MainActivity.this);
        rxPermission
                .requestEach(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            if (permission.name.contains("android.permission.CAMERA")) {

                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Log.d("TAG", permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Log.d("TAG", permission.name + " is denied.");
                        }
                    }
                });

    }

    private void bannerInit() {

        String menuList = (String) SharedPreferencesUtils.getParam(this, "menu_list", "");
        Type menuListType = new TypeToken<List<MenuBean>>() {
        }.getType();
        List<MenuBean> menulist = gson.fromJson(menuList, menuListType);
        List<MenuBean> allTwoList = new ArrayList<>();
        allTwoList.addAll(menulist);
        allTwoList.addAll(menulist);
        List<MenuBean> imgelist = new ArrayList<>();
        for (int i = 0; i < allTwoList.size(); i++) {

            if (allTwoList.get(i).getIs_show().equals("1") || allTwoList.get(i).getIs_show().equals("")) {
                imgelist.add(allTwoList.get(i));
            }
        }
        activityMainBinding.bannerView.setAdapter(new SimpleAdapter())
                .registerLifecycleObserver(getLifecycle())
                .setRevealWidth(Constant.Left, Constant.Right)
//                .setRevealWidth(BannerUtils.dp2px(306f))
                .setPageStyle(PageStyle.MULTI_PAGE_SCALE)

                .setOnPageClickListener(
                        (clickedView, position) -> {
                            menuBean = imgelist.get(position);
                            if (menuBean.getCode().equals("smjt")) {

                                regCheck(1);
                            } else if (menuBean.getCode().equals("smqh")) {
                                regCheck(2);
                            } else if (menuBean.getCode().equals("sjhjt")) {

                            } else if (menuBean.getCode().equals("sz")) {
                                if (!Constant.DEBUG) {
                                    MyDialog myDialog = MyDialog.newInstanceCon2("输入密码", "", "确认", "", "show", true);
                                    myDialog.show(getSupportFragmentManager(), "MyDialog");

                                    myDialog.setMyDialogListener(new MyDialog.MyDialogListener() {
                                        @Override
                                        public void onPositiveClick() {
                                            if (myDialog.getInputEditText().equals("Admin123")) {
                                                myDialog.dismiss();
                                                startActivity(new Intent(MainActivity.this, SetActivity.class));
                                            } else {
                                                myDialog.dismiss();
                                                MyDialog myDialog1 = MyDialog.newInstance2("提示", "密码错误", "", "", true);
                                                myDialog1.show(getSupportFragmentManager(), "MyDialog");
                                            }
                                        }

                                        @Override
                                        public void onNegativeClick() {
                                        }
                                    });
                                } else {
                                    startActivity(new Intent(MainActivity.this, SetActivity.class));
                                }
                            }
                        }
                )
                .registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                    @Override
                    public void onPageSelected(int position) {
                        super.onPageSelected(position);
                        mHandler.removeMessages(6);
                        SimpleAdapter adapter = (SimpleAdapter) activityMainBinding.bannerView.getAdapter();
                        adapter.setSelectedPosition(position);
                        mHandler.sendEmptyMessageDelayed(6, 120000);
                    }
                })
                .setAutoPlay(false)
                .setIndicatorVisibility(View.GONE)
                .create(imgelist);
        activityMainBinding.bannerView.removeDefaultPageTransformer();

    }

    @Override
    protected void onResume() {
        super.onResume();
//        hideBottomUIMenu();
        Intent mIntent = new Intent();
        mIntent.setAction("com.xinxing.statusbar");
        mIntent.putExtra("status_bar", false);
        sendBroadcast(mIntent);
        mHandler.sendEmptyMessageDelayed(13, 1500);
        mHandler.sendEmptyMessageDelayed(5, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        runing = false;
//        deviceKernel.stop();
    }

    int pi = 2;
    int over = 1;
    private boolean hasTou = false;
    Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    BucketType bucketType = (BucketType) msg.obj;
                    comChooseHideOne(_mainTanView);
                    Log.e("TTT", "第一次拍照");
                    comPutiShow(_mainTanView, bucketType);
                    if (!Constant.DEBUG) {
                        activityMainBinding.simplePreview.removeAllViews();
                        SimplePreviewBig.id = positionNum;
                        simplePreview = new SimplePreviewBig(MainActivity.this);
                        activityMainBinding.simplePreview.addView(simplePreview);
                    }
                    Message msg3 = new Message();
                    msg3.obj = 1;
                    msg3.what = 8;
                    mHandler.sendMessageDelayed(msg3, 1000);
                    if (Constant.INIT_HK) {
                        if (videoSet != null && !Constant.MOCK) {
                            videoSet.takePicture1(1, "");
                        }
                    }
                    break;
                case 2://读取rfid
                    deviceKernel.getRfid().singleRfid();
                    mHandler.sendEmptyMessageDelayed(2, 2000);
                    break;
                case 3:
                    if (tx5 != null) {
                        float f = (float) (secondWeight);
                        int s = (int) ((f / Integer.valueOf(capaity)) * 100);
                        tx5.setText(s + "%");

                        DecimalFormat decimalFormat = new DecimalFormat("#0.00"); // 创建 DecimalFormat 对象并设置格式模式 "#0.00"
                        String formattedNumber = decimalFormat.format((float) (secondWeight - firstWeight));
                        speek(formattedNumber);
                        TextView tx4 = findViewById(R.id.comPutiText5);
                        String formattedNumber2 = decimalFormat.format((float) (Integer.valueOf(capaity) - secondWeight));
                        tx4.setText("预计最多还可以交投" + formattedNumber2 + "公斤");

                        float k = (int) ((f / Integer.valueOf(capaity)) * 100);
                        multiWaveHeader.setProgress((k / 100));
                        multiWaveHeader.start();
                    }
                    break;
                case 4:
                    Log.e("OrderManager", "第二次重量：" + positionNum);
                    serialSendReceiveData.getWeight(positionNum, (num, weight) -> {
                        secondWeight = (float) weight / 1000;
                        float isShap = secondWeight - firstWeight;
                        if (isShap > 0.05 && !hasTou) {
                            Log.e("OrderManager", "第二次重量为：" + weight);
                            hasTou = true;
                            Log.e("kong", "第二次拍照>>");
                            Message msg4 = new Message();
                            msg4.obj = 2;
                            msg4.what = 12;
                            mHandler.sendMessage(msg4);
                        }
                        mHandler.sendEmptyMessageDelayed(4, 1000);

                        mHandler.sendEmptyMessage(3);
                    });
                    break;
                case 5:
                    getWeight.getWeight();
                    break;
                case 6:
                    activityMainBinding.bannerView.setCurrentItem(0);
                    break;
                case 7:
                    countDown--;
                    if (countDown >= 0) {
                        countdownTextView.setText("结束投递\n(" + (String.valueOf(countDown)) + "s)");
                        if (countDown == 0) {
                            runing = false;
                            comPutiHide(_mainTanView);
                            orderSub(_mainTanView);
                        }
                    } else {
                        runing = false;
                        comPutiHide(_mainTanView);
                        orderSub(_mainTanView);
                    }
                    break;
                case 8:

                    int item = (int) msg.obj;
                    if (simplePreview != null) {
                        simplePreview.take(MainActivity.this, item);
                    } else {
                        Log.e("photo", "simplePreview null");
                    }

                    break;
                case 9:
                    ordcommp(RecoveryApplication.getInstance().getOrderCode(), positionNum);
                    break;
                case 11:
                    over++;
                    if (over < 15) {
                        serialSendReceiveData.overflow(new IOverFlowListener() {
                            @Override
                            public void overFlowState(boolean num1, boolean num2, boolean num3, boolean num4) {
                                Log.e("YYY", "门是否满溢" + num1);

                            }
                        });
                        mHandler.sendEmptyMessageDelayed(11, 500);
                    } else {
                        mHandler.removeMessages(11);
                    }
                    break;
                case 12:
                    if (!Constant.DEBUG) {
                        activityMainBinding.simplePreview.removeAllViews();
                        SimplePreviewBig.id = positionNum;
                        simplePreview = new SimplePreviewBig(MainActivity.this);
                        activityMainBinding.simplePreview.addView(simplePreview);
                    }
                    Message msg4 = new Message();
                    msg4.obj = msg.obj;
                    msg4.what = 8;
                    mHandler.sendMessage(msg4);
                    if (Constant.INIT_HK) {
                        Log.e("photo", "海康拍照" + (Integer) msg4.obj);
                        if (videoSet != null && !Constant.MOCK) {
                            videoSet.takePicture1((Integer) msg.obj, "");
                        }
                    } else {
                        Log.e("photo", "海康拍照初始化失败" + (Integer) msg4.obj);
                    }
                    break;
                case 13:
                    if (bucketTypes != null && bucketTypes.size() > 0) {
                        for (BucketType bucketType1 : bucketTypes) {
                            Log.e("yujs", "门编号：" + bucketType1.getNum());
                            if (appRuntime.getAnyWeight().containsKey(bucketType1.getNum())) {
                                Log.e("yujs", "重量 " + appRuntime.getAnyWeight().get(bucketType1.getNum()));
                            }
                            if (appRuntime.getAnyWeight().size() > 0 && appRuntime.getAnyWeight().containsKey(bucketType1.getNum())) {
                                bucketType1.setWeight(appRuntime.getAnyWeight().get(bucketType1.getNum()));
                            } else {
                                bucketType1.setWeight(0);
                            }
                        }

                        categoryAdapter.setmDatas(bucketTypes);
                        baseView.setList(bucketTypes);

                    }
                    break;
                case MSG_COLSE_CUT:
                    serialSendReceiveData.closeCut(1);
                    break;
                case MSG_COLSE_DOOR_WEIGHT:
                    serialSendReceiveData.getWeight(positionNum, new ICallBackWeight() {
                        @Override
                        public void setWeight(int num, long weight) {
                            secondWeight = (float) weight / 1000;
                            mHandler.sendEmptyMessage(9);
                            Log.e("main", "交投门关闭后，查询重量");
                        }
                    });
                    break;
                case MSG_SEND_HEART:
                    baseView.reportTime();
                    break;
                case MSG_DELAYED_HK:
                    if (!Constant.DEBUG) {
                        videoSet = new VideoSet(MainActivity.this);
                    }
                    break;
                case MSG_HIDE_NOTIFY:
                    activityMainBinding.llyZip.setVisibility(View.GONE);
                    break;
                case MSG_HIDE_OVER:
                    Log.e("TTT","桶未满  "+positionNum);
                    Constant.OVERRLOW.put(positionNum,0);
                    bucketTypes.get(positionNum - 1).setOverFlowStatus("f");
                    break;
            }

        }
    };

    private void speek(String formattedNumber) {

        String ops_putp = (String) SharedPreferencesUtils.getParam(MainActivity.this, "ops_weight", "");
        if (!ops_putp.equals("")) {
            Type dev = new TypeToken<SetWeightChange>() {
            }.getType();
            Gson gson = new Gson();
            SetWeightChange weightChange = gson.fromJson(ops_putp, dev);
            if (weightChange.getTopTitle().equals("")) {
                if (secondWeight < firstWeight) {
                    tx1.setText("您已交投0.00kg");
                } else {
                    tx1.setText("您已交投" + (formattedNumber) + "kg");
                }
            } else {
                tx1.setText(weightChange.getTopTitle().replace("XX", formattedNumber));
            }
            if (weightChange.isTopAi()) {
                ttsService.speak(tx1.getText().toString());
            }
        } else {
            if (secondWeight < firstWeight) {
                tx1.setText("您已交投0.00kg");
            } else {
                tx1.setText("您已交投" + (formattedNumber) + "kg");
            }
        }
    }

    private TextView tx5, tx1;
    private String capaity;
    private boolean runing = false;
    private MultiWaveHeader multiWaveHeader;

    private void comPutiShow(View view, BucketType bucketType) {
        mHandler.sendEmptyMessageDelayed(4, 1000);
        hasTou = false;
        runing = true;
        add_once = 3;
        LinearLayout comPuti = findViewById(R.id.mainTanPuti);
        comPuti.setVisibility(View.VISIBLE);
        TextView tx2 = findViewById(R.id.comPutiText2);
        tx2.setText(bucketType.getRecycleCataName());
        tx1 = findViewById(R.id.comPutiText1);
        TextView tx3 = findViewById(R.id.comPutiText3);
        tx3.setText(bucketType.getDefaultPkgPrice() + "/" + bucketType.getUnitName());

        LinearLayout jqCon = findViewById(R.id.jqCon);
        if (positionNum == 1) {
            jqCon.setVisibility(View.VISIBLE);
        } else {
            jqCon.setVisibility(View.GONE);
        }

        //获取桶的容量
        capaity = bucketType.getCapacity();
        TextView tx4 = findViewById(R.id.comPutiText5);
        tx4.setText("预计最多还可以交投" + (Integer.valueOf(capaity) - firstWeight) + "公斤");
        //语音
        String ops_putp = (String) SharedPreferencesUtils.getParam(MainActivity.this, "ops_weight", "");
        if (!ops_putp.equals("")) {
            Type dev = new TypeToken<SetWeightChange>() {
            }.getType();
            Gson gson = new Gson();

            SetWeightChange weightChange = gson.fromJson(ops_putp, dev);
            if (weightChange.isBottomAi()) {
                if (!weightChange.getBottomText().equals("")) {
                    ttsService.speak(weightChange.getBottomText());
                }
            }
            //底部
            TextView tx8 = findViewById(R.id.comPutiText8);
            tx8.setText(weightChange.getBottomText());
        }
        countdownTextView = findViewById(R.id.comPutiText7);
        countdownTextView.setText("结束投递\n(" + (String.valueOf(120)) + "s)");
        tx5 = findViewById(R.id.comPutiText6);
        float f = (float) (firstWeight);

        float s = (int) ((f / Integer.valueOf(capaity)) * 100);
        tx5.setText((int) s + "%");
        multiWaveHeader = findViewById(R.id.waveHeader2);
        multiWaveHeader.setProgress(s / 100);//注意：参数必须是float 类型，小数点后；例如：.2f即20% 否则不显示
        multiWaveHeader.start();
        countDown = 30;
//        countDownTimer2.start();
        Thread downTime = new Thread() {
            @Override
            public void run() {
                super.run();
                while (runing) {
                    try {
                        sleep(1000);
                        mHandler.sendEmptyMessage(7);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        downTime.start();
//
    }

    int add_once = 3;

    public void addOrdTime(View view) {
        add_once--;
        if (add_once < 0) {
            Tools.logTips("增加时间已到上线，无法再增加时间！", getSupportFragmentManager());
        } else {
            countDown += 30;
        }
    }

    private void subOrderStatus(String str) {
        Map<String, Object> par = new HashMap<>();
        par.put("code", RecoveryApplication.getInstance().getOrderCode());
        par.put("status", str);
        new BaseTask<>(this, RetroFactory.getJsonService().subOrderStatus(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener() {


            @Override
            public void onSuccess(Object o) {

            }

            @Override
            public void onFail() {

            }
        });
    }

    public void qjBtn(View view) {
        TextView jqText = findViewById(R.id.jqText);
        if (jqText.getText().toString().equals("打开剪切")) {
            serialSendReceiveData.openCut(positionNum);
            jqText.setText("关闭剪切");
        } else {
            serialSendReceiveData.closeCut(1);
            jqText.setText("打开剪切");
        }
    }

    public void orderSub(View view) {
        try {
            //orderInfo.iscut = false;
//            isShap = 0;
            runing = false;
            float all = secondWeight - firstWeight;
            Log.e("TTT", "点击提交   " + all);
            if (positionNum == 1) {
                mHandler.sendEmptyMessageDelayed(MSG_COLSE_CUT, 500);//关剪切
                if (all <= 0.1) {
                    subOrderStatus("11");
                    goOut();
                    jtSuccess = false;
                    activityMainBinding.tvDiglog.setVisibility(View.GONE);
                    return;
                }
            }
            if (all < 0.05) {
                subOrderStatus("11");
                goOut();
                jtSuccess = false;
                activityMainBinding.tvDiglog.setVisibility(View.GONE);

            } else {
                serialSendReceiveData.closeDoor(positionNum);
                countDownTimer2.cancel();
                comPutiHide(_mainTanView);
                activityMainBinding.tvDiglog.setVisibility(View.VISIBLE);
                jtSuccess = true;
                Message msg4 = new Message();
                msg4.obj = 3;
                msg4.what = 12;
                mHandler.sendMessage(msg4);


            }
        } catch (Exception e) {
            Log.e("TTT", "错误" + e.getMessage());
        }
    }

    //退出
    public void goOut() {
        //关闭弹窗
        comLoginHide(_mainTanView);
        comChooseHideOne(_mainTanView);

        comPutiHide(_mainTanView);
        isTan = false;
//        isShap = 0;
//
//        videoSet.close();

        //取消订单
        serialSendReceiveData.closeDoor(positionNum);
        mHandler.sendEmptyMessageDelayed(11, 500);

    }

    public void comPutiHide(View view) {
        isTan = false;
        _mainTanView = findViewById(R.id.mainTanPuti);
        _mainTanView.setVisibility(View.GONE);
        ttsService.interrupt();
        countDownTimer2.cancel();
        mHandler.removeMessages(4);
    }

    /**
     * 跳转链接
     */
    public void urlTz() {
        MyDialog myDialog = MyDialog.newInstance("提示", "此回收柜还没有入网登记，请先登记！", "登记", "取消");
        myDialog.setMyDialogListener(new MyDialog.MyDialogListener() {
            @Override
            public void onPositiveClick() {
                myDialog.dismiss();
                Intent intent = new Intent(MainActivity.this, SetActivity.class);
                startActivity(intent);
            }

            @Override
            public void onNegativeClick() {
                myDialog.dismiss();
            }
        });
        myDialog.show(getSupportFragmentManager(), "MyDialog");
    }

    private int viewtype = 0;

    CountDownTimer countDownTimer2 = new CountDownTimer(120000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (viewtype == 1) {
                countdownTextView.setText("退出(" + millisUntilFinished / 1000 + "s)");
            }
            if (viewtype == 2) {
                countdownTextView.setText("结束投递\n(" + (String.valueOf(millisUntilFinished / 1000)) + "s)");
            }
        }

        @Override
        public void onFinish() {
            if (viewtype == 1) {
                countdownTextView = findViewById(R.id.comChooseText2);
                _mainTanView.setVisibility(View.GONE);
                ttsService.interrupt();
                viewtype = 0;
            }
            if (viewtype == 2) {
                viewtype = 0;
                comPutiHide(_mainTanView);
                orderSub(_mainTanView);
            }
        }
    };

    /*选择弹窗倒计时部分*/
    public void comChooseShow(View view) {

        isTan = true;
        _mainTanView = findViewById(R.id.mainTanChoose);
        countdownTextView = findViewById(R.id.comChooseText2);
        _mainTanView.setVisibility(View.VISIBLE);
        countDownTimer2.start();
        viewtype = 1;
        SetCategory setCategory;
        String str = (String) SharedPreferencesUtils.getParam(this, "ops_category", "");
        if (!str.equals("")) {
            Type dev = new TypeToken<SetCategory>() {
            }.getType();
            Gson gson = new Gson();
            setCategory = gson.fromJson(str, dev);
            String yyStr = "";
            if (setCategory.isTopAi()) {
                yyStr += setCategory.getTopTitle();
            }

            if (setCategory.isBottomAi()) {
                yyStr += setCategory.getBottomText();
            }
            ttsService.speak(yyStr);
        }
        pageInit();
    }

    private int positionNum = 1;//桶号

    private void pageInit() {

        RecyclerView recyclerView2 = findViewById(R.id.recycler2);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2, RecyclerView.VERTICAL, false);
        recyclerView2.setLayoutManager(gridLayoutManager);
        SpaceItemDecoration spaceItemDecoration = new SpaceItemDecoration(1, 1);
        recyclerView2.addItemDecoration(spaceItemDecoration);
        CategoryAdapter categoryAdapter2 = new CategoryAdapter(R.layout.adapter_category, BR.bucket, this);
        recyclerView2.setAdapter(categoryAdapter2);
        categoryAdapter2.setmDatas(bucketTypes);
        categoryAdapter2.setOnItemClickListener((view, position) -> {
            positionNum = bucketTypes.get(position).getNum();
            String name = bucketTypes.get(position).getRecycleCataName();
            String f = bucketTypes.get(position).getOverFlowStatus();
            if (Constant.OVERRLOW.containsKey(positionNum)) {
                Log.e("TTT", positionNum + "Over   ---->>>>>> " + Constant.OVERRLOW.get(positionNum));
                if (Constant.OVERRLOW.get(positionNum) == 1) {
                    bucketTypes.get(position).setOverFlowStatus("t");
                    activityMainBinding.llyZip.setVisibility(View.VISIBLE);
                    activityMainBinding.title1.setText("桶已满，无法交投");
                    mHandler.removeMessages(MSG_HIDE_NOTIFY);
                    mHandler.sendEmptyMessageDelayed(MSG_HIDE_NOTIFY, 5000);
                    return;
                } else {
                    bucketTypes.get(positionNum - 1).setOverFlowStatus("f");
                }
                baseView.setList(bucketTypes);
                SharedPreferencesUtils.setParam(MainActivity.this, "bucket", gson.toJson(bucketTypes));

            }
            if (bucketTypes.get(position).getCompressStatus() != null && bucketTypes.get(position).getCompressStatus().equals("01")) {
                activityMainBinding.llyZip.setVisibility(View.VISIBLE);
                activityMainBinding.title1.setText("正在压缩");
                mHandler.removeMessages(MSG_HIDE_NOTIFY);
                mHandler.sendEmptyMessageDelayed(MSG_HIDE_NOTIFY, 5000);
            } else {
                orderSelMenu(bucketTypes.get(position), positionNum);
                getCataType(bucketTypes.get(position), RecoveryApplication.getInstance().getOrderCode());
            }
        });

    }

    private float firstWeight = 0;//初始重量
    private float secondWeight = 0;//投递后重量
    public static VideoSet videoSet;

    public void orderSelMenu(BucketType bucket, int num) {

        serialSendReceiveData.getWeight(num, new ICallBackWeight() {
            @Override
            public void setWeight(int num, long weight) {
                firstWeight = (float) weight / 1000;
//                serialSendReceiveData.overflow();\\
                Log.e("TT", "第一次开门");
                serialSendReceiveData.openDoor(num);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = bucket;
                mHandler.sendMessage(msg);

            }
        });

    }

    /**
     * "跳转恭喜界面
     *
     * @param yzCode
     * @param i
     */
    public void ordcommp(String yzCode, Integer i) {
        float all = secondWeight - firstWeight;
        Log.e("main", "跳转恭喜界面  最后一次重量差值 " + all);
        if (positionNum == 1 && all <= 0.1) {
            subOrderStatus("11");
            goOut();
            activityMainBinding.tvDiglog.setVisibility(View.GONE);
            return;
        }
        if (all < 0.05) {
            subOrderStatus("11");
            goOut();
            activityMainBinding.tvDiglog.setVisibility(View.GONE);
            return;
        }
        subOrderStatus("02");
        Map<String, Object> par = new HashMap<>();
        par.put("code", RecoveryApplication.getInstance().getOrderCode());
        DecimalFormat decimalFormat = new DecimalFormat("#0.00"); // 创建 DecimalFormat 对象并设置格式模式 "#0.00"
        String formattedNumber = decimalFormat.format((float) (all));
        par.put("weight", Float.valueOf(formattedNumber));
        Log.e("main", "获取");
        new BaseTask<order>(this, RetroFactory.getJsonService().subOrder(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener<order>() {


            @Override
            public void onSuccess(order o) {
                RecoveryApplication.getInstance().setYhCode(o.getCode());
                updataYD();//提交
                activityMainBinding.tvDiglog.setVisibility(View.GONE);
                Log.e("main", "三次拍照完成>>提交图片");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(MainActivity.this, CompOrderActivity.class);
                        intent.putExtra("orderCode", RecoveryApplication.getInstance().getOrderCode());

                        startActivity(intent);
                    }
                });
            }

            @Override
            public void onFail() {

            }
        });
        Log.e("kong", "第三次拍照提交>>");

    }

    /**
     * 创建订单
     */
    public void addOrder() {
        try {
            Map<String, Object> par = new HashMap<>();
            par.put("cabinetCode", deviceKernel.getRuntime().getCabinet().getCode());
            if (par.get("cabinetCode").equals("")) {
                Tools.logTips("创建订单失败！", getSupportFragmentManager());
                return;
            }
            new BaseTask<order>(this, RetroFactory.getJsonService().orderCreate(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener<order>() {
                @Override
                public void onSuccess(order o) {
                    TextView textView = findViewById(R.id.jqText);
                    textView.setText("打开剪切");
                    RecoveryApplication.getInstance().setOrderCode(o.getCode());
                    //进行录像
                    //videoSet.hkStartRecode();

                    if (deviceType == 1) {
                        comChooseShow(_mainTanView);
                    } else {
                        getCataType(deviceKernel.getRuntime().getBuckes().get(0), o.getCode());
                        Log.e("TTT", "订单生成开始交投");
                        orderSelMenu(deviceKernel.getRuntime().getBuckes().get(0), positionNum);
                    }

                }

                @Override
                public void onFail() {

                }
            });

        } catch (Exception e) {
            Tools.logTips(e.getMessage() + "1", getSupportFragmentManager());
        }

    }

    private void getCataType(BucketType bucket, String code) {
        Map<String, Object> par = new HashMap<>();
        par.put("code", code);
        par.put("recycleCataCode", bucket.getRecycleCataCode());
        par.put("bucketCode", bucket.getCode());
        new BaseTask<>(this, RetroFactory.getJsonService().subCatatype(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener() {

            @Override
            public void onSuccess(Object o) {

            }

            @Override
            public void onFail() {

            }
        });
    }

    private void regCheck(int type) {

        ProgressBar progressBar = findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);
        if (deviceKernel.getRuntime().getCabinet() != null) {
            String cabinetCode = deviceKernel.getRuntime().getCabinet().getCode();

            if (cabinetCode == "") {
                /*桶注册界面*/
                progressBar.setVisibility(View.GONE);
                urlTz();
            } else {
                comLoginShow(_mainTanView, type);
            }
        } else {
            progressBar.setVisibility(View.GONE);
            urlTz();
        }
    }

    /**
     * 固定效果部分
     */
    /*二维码弹窗倒计时部分*/
    public void comLoginShow(View view, int type) {

        isTan = true;

        ConstraintLayout _mainTanView = findViewById(R.id.mainTanLogin);
        _mainTanView.setVisibility(View.VISIBLE);

        //顶部文案
        String yyStr = "";
        TextView topT = findViewById(R.id.comLoginText2);
        String topT_c = menuBean.getTop_text();
        if (!topT_c.equals(""))
            topT.setText(topT_c);
        if (menuBean.getTop_ai().equals("1"))
            yyStr += topT_c;

        TextView botT = findViewById(R.id.comLoginText4);
        String botT_c = menuBean.getBot_text();
        if (!botT_c.equals(""))
            botT.setText(botT_c);
        if (menuBean.getBot_ai().equals("1"))
            yyStr += botT_c;


        if (!yyStr.equals(""))
            ttsService.speak(yyStr);

        countdownTextView = findViewById(R.id.comLoginText);

        loginErm(_mainTanView, type);
    }

    /**
     * 登录二维码
     */
    public void loginErm(View view, int type) {

        Map<String, Object> par = new HashMap<>();
        if (type == 1) {
            par.put("endpointType", "dev");
        }
        par.put("expires", 120);

        ProgressBar progressBar = findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE); // 显示加载动画
        if (type == 1) {
            new BaseTask<QrMessage>(this, RetroFactory.getJsonService().getQrcode(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener<QrMessage>() {

                @Override
                public void onSuccess(QrMessage qrMessage) {
                    progressBar.setVisibility(View.GONE);
                    String qrcode = qrMessage.getQrcode();
                    loginCode = qrMessage.getLoginCode();
                    ermCreateM(qrcode, type);
                }

                @Override
                public void onFail() {
                    progressBar.setVisibility(View.GONE);
                }
            });


        } else {
            new BaseTask<QRCodeClean>(this, RetroFactory.getJsonService().cleanScan(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener<QRCodeClean>() {
                @Override
                public void onSuccess(QRCodeClean cleanQRCode) {
                    progressBar.setVisibility(View.GONE);
                    cleanCode = cleanQRCode.getQrcode();
                    ermCreateM(cleanQRCode.getQrcode(), type);
                    Log.e("Kong", "生成清运二维码cleancode:   " + cleanQRCode);
                }

                @Override
                public void onFail() {
                    progressBar.setVisibility(View.GONE);
                }
            });
        }


    }

    private int deviceType = 0;//0 单筒，1 多桶

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onKernelEvent(KernelAction kernelAction) {
        int actionType = kernelAction.getActionType();
        List<String> params = kernelAction.getActionParams();
        switch (actionType) {
            case KernelActions.RFID_READ:

                upDataRf(bucketTypes, getRfid());
                break;
            case KernelActions.INIT_FINISH:
                bucketTypes.clear();
                String bucketStr = (String) SharedPreferencesUtils.getParam(this, "bucket", "");
                if (!bucketStr.equals("")) {
                    Type dev = new TypeToken<List<BucketType>>() {
                    }.getType();
                    bucketTypes = gson.fromJson(bucketStr, dev);
                }
                Map<String, Boolean> bmp = new HashMap<>();
                String categoryStr = (String) SharedPreferencesUtils.getParam(MainActivity.this, "set_category", "");
                if (!categoryStr.equals("")) {
                    Type dev = new TypeToken<List<Catalogs>>() {
                    }.getType();
                    Gson gson = new Gson();
                    ;
                    List<Catalogs> catalogs = gson.fromJson(categoryStr, dev);
                    for (Catalogs item : catalogs) {
                        bmp.put(item.getCode(), item.isShow());
                    }
                }
                Log.e("SSS", bucketTypes.size() + " ");
                List<BucketType> items = new ArrayList<>();
                for (BucketType item : bucketTypes) {
                    if (bmp.get(item.getRecycleCataCode()))
                        items.add(item);
                }
                Log.e("SSS", items.size() + " ?");
                bucketTypes.clear();
                bucketTypes.addAll(items);
                if (bucketTypes.size() > 1) {
                    deviceType = 1;
                    GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2, RecyclerView.VERTICAL, false);
                    activityMainBinding.recycler.setLayoutManager(gridLayoutManager);
                    SpaceItemDecoration spaceItemDecoration = new SpaceItemDecoration(1, 1);
                    activityMainBinding.recycler.addItemDecoration(spaceItemDecoration);
                } else {
                    deviceType = 0;
                    activityMainBinding.recycler.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
                }
                for(int i =0;i<bucketTypes.size();i++){

                    if(bucketTypes.get(i).getName()!=null&&bucketTypes.get(i).getName().equals("纸类")){
                        bucketTypes.get(i).setCompressStatus("00");
                        SetBaseView.buckets = bucketTypes;
                        SharedPreferencesUtils.setParam(MainActivity.this, "bucket", gson.toJson(bucketTypes));
                    }
                }
                categoryAdapter.setmDatas(bucketTypes);
                mHandler.sendEmptyMessageDelayed(13, 1000);
                break;
            case KernelActions.CREAT_ORDER:
                addOrder();
                break;
            case KernelActions.TTS_END:

                break;
            case KernelActions.CLEAN_DOOR_START:
                int open = 1;
                if (params != null) {
                    open = Integer.valueOf(params.get(0));
                }
                Log.e("main", "收到关闭清运门：" + open);
                if (Constant.CLEAN_DOOR_STATE.containsKey(open)) {
//                    if (!uprfid && Constant.CLEAN_DOOR_STATE.get(open) == 00) {
//                        serialSendReceiveData.openLock(open);
//                    }
                    if (bucketTypes.size() > (open - 1)) {
                        bucketTypes.get(open - 1).setOverFlowStatus("f");
                        bucketTypes.get(open - 1).setWeight(0);
                        Constant.OVERRLOW.put(open, 0);
                        baseView.setList(bucketTypes);
                        SharedPreferencesUtils.setParam(MainActivity.this, "bucket", gson.toJson(bucketTypes));
                    }
                }
                break;
            case KernelActions.DOOR_START:
                if (Constant.DOOR_STATE.containsKey(positionNum)) {
                    int c = Constant.DOOR_STATE.get(positionNum);
                    Log.e("main", c + "  交投门关闭判断  " + jtSuccess);
                    if (c == 0 && jtSuccess) {
                        mHandler.sendEmptyMessage(MSG_COLSE_DOOR_WEIGHT);

                    }
                }
                break;
            case KernelActions.OVERRLOW:
                if (Constant.OVERRLOW.containsKey(positionNum)) {
                    Log.e("main", positionNum + "Over   ---->>>>>> " + Constant.OVERRLOW.get(positionNum));
                    if (Constant.OVERRLOW.get(positionNum) == 1) {
                        Log.e("TTT","满溢=====");
                        mHandler.removeMessages(MSG_HIDE_OVER);
                        mHandler.sendEmptyMessageDelayed(MSG_HIDE_OVER,11000);
                        bucketTypes.get(positionNum - 1).setOverFlowStatus("t");
                    } else {
                        bucketTypes.get(positionNum - 1).setOverFlowStatus("f");
                    }
                    baseView.setList(bucketTypes);

                }
                break;
            case KernelActions.ZIP:
                for (int i = 0; i < bucketTypes.size(); i++) {

                    if (bucketTypes.get(i).getName().equals("纸类")) {
                        bucketTypes.get(i).setCompressStatus("01");
                        baseView.setList(bucketTypes);

                    }
                }
                countDownTimer3.cancel();
                countDownTimer3.start();
                break;
            case KernelActions.LOG:
//                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//                dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
//                String content = dateFormat.format(new Date());
//                if (params.size() > 0) {
////                    appendLog(content+"："+params.get(0));
////                    LogWriter.writeLog(MainActivity.this, "tag", content + "：" + params.get(0));
//                }
                break;
        }

    }

    public void ermCreateM(String code, int type) {
        try {
            ErmCreate erm = new ErmCreate();
            Bitmap bitmap = erm.generateQRCode(this, code, 200, 200);
            ImageView imageView = findViewById(R.id.icon_loginerm);
            imageView.setImageBitmap(bitmap);
            countTimer(_mainTanView, 1, type);
        } catch (WriterException e) {
            System.out.print("Failed to generate QR Code" + e.getMessage());
        }
    }

    /*倒计时*/
    private void countTimer(LinearLayout view, Integer num, int type) {
        // 设置倒计时的总时间（单位：毫秒）
        int totalTime = 120000;
        if (!menuBean.getAuto_out_time().isEmpty() && Integer.parseInt(menuBean.getAuto_out_time().toString()) > 0) {
            totalTime = Integer.parseInt(menuBean.getAuto_out_time().toString()) * 1000;
        }
        // 设置倒计时的间隔时间（单位：毫秒）
        int interval = 1000;
        countDownTimer = new CountDownTimer(totalTime, interval) {
            @Override
            public void onTick(long millisUntilFinished) {
                long seconds = millisUntilFinished / 1000;
                countdownTextView.setText("退出(" + (String.valueOf(seconds)) + "s)"); // 更新TextView显示的时间
                //类型为1则需要判断是否登录成功 3秒判断一次
                if (num == 1 && seconds % 5 == 0 && (loginCode != null || cleanCode != null)) {
                    if (type == 1)
                        loginCheck();
                    else if (type == 2) {
                        clearCheck(cleanCode);
                    }
                }
            }

            @Override
            public void onFinish() {
                comLoginHide(_mainTanView);
            }
        };
        countDownTimer.start();
    }

    private void loginSuccess(String token) {
        try {
            countDownTimer.cancel();
            Log.e("kong", "token " + token);
            RecoveryApplication.getInstance().setToken(token);
            comLoginHide(_mainTanView);
            /*创建订单*/
            addOrder();

        } catch (Exception e) {
            Tools.logTips(e.getMessage(), getSupportFragmentManager());
        }
    }

    /*登录成功判断*/
    private void loginCheck() {
        new BaseTask<LoginCheck>(this, RetroFactory.getJsonService().getLoginCheck(loginCode)).handleResponse(new BaseTask.ResponseListener<LoginCheck>() {
            @Override
            public void onSuccess(LoginCheck loginCheck) {
                if (loginCheck.getStatus().equals("01")) {
                    loginSuccess(loginCheck.getResult().getToken());

                }
            }

            @Override
            public void onFail() {

            }
        });
    }

    public void comChooseHideOne(View view) {
        countDownTimer2.cancel();
        isTan = false;
        _mainTanView = findViewById(R.id.mainTanChoose);
        if (countDownTimer != null) countDownTimer.cancel();
        _mainTanView.setVisibility(View.GONE);
        ttsService.interrupt();
    }

    private void clearCheck(String qr) {
        Log.e("Kong", "检查清运二维码结果: " + qr);
        new BaseTask<CleanQRCode>(this, RetroFactory.getJsonService().getCleanScan(qr)).handleResponse(new BaseTask.ResponseListener<CleanQRCode>() {

            @Override
            public void onSuccess(CleanQRCode cleanQRCode) {
                if (cleanQRCode.getStatus().equals("01")) {
                    RecoveryApplication.getInstance().setToken(cleanQRCode.getIdentityToken());
                    countDownTimer.cancel();
                    comLoginHide(_mainTanView);
                    getCleanOrder(cleanQRCode.getCleanOrderCode());
                }
            }

            @Override
            public void onFail() {

            }
        });
    }

    private List<String> getRfid() {
        List<String> rfids = deviceKernel.getRfid().getRfid();

        return rfids;
    }

    private boolean uprfid = false;//绑定完rfid 后才运行关门

    private void upDataRf(List<BucketType> bucketTypes, List<String> rfids) {
        String rfidcate = (String) SharedPreferencesUtils.getParam(MainActivity.this, "rfid", "");
        List<String> rfidCatas = null;
        if (rfidcate.equals("")) {
            rfidCatas = new ArrayList<>();
        } else {
            Type cType = new TypeToken<List<String>>() {
            }.getType();
            rfidCatas = gson.fromJson(rfidcate, cType);
        }
        List<Catalogs> catalogs = appRuntime.getCatalogs();
        Map<String, String> cataMap = new HashMap<>();
        for (Catalogs catalog : catalogs) {
            cataMap.put(catalog.getName(), catalog.getIdCodePrefix());
        }
        for (BucketType bucketType : bucketTypes) {
            for (String rfid : rfids) {
                if (cataMap.containsKey(bucketType.getRecycleCataName())) {

                    if (rfid.substring(12, 13).toUpperCase().equals(cataMap.get(bucketType.getRecycleCataName()))) {
                        Map<String, Object> par = new HashMap<>();
                        par.put("code", bucketType.getCode());
                        String item = rfid.substring(12, rfid.length()).toUpperCase();
                        par.put("rfidCode", item);
                        if (rfidCatas.contains(item)) {
                            Log.e("RFIDM", "重复绑定");
                        } else {
                            boolean isRepeat = false;
                            for (int i = 0; i < rfidCatas.size(); i++) {
                                if (rfidCatas.get(i).substring(0, 1).equals(cataMap.get(bucketType.getRecycleCataName()))) {
                                    rfidCatas.set(i, item);
                                    isRepeat = true;
                                }
                            }
                            if (!isRepeat) {
                                rfidCatas.add(item);
                            }
                            SharedPreferencesUtils.setParam(MainActivity.this, "rfid", gson.toJson(rfidCatas));
                            Log.e("RFIDM", "------>>>" + gson.toJson(rfidCatas));
                            appRuntime.setNowRfid(rfidCatas);
                            new BaseTask<BaseEntity>(this, RetroFactory.getJsonService().upRIDCode(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener<BaseEntity>() {
                                @Override
                                public void onSuccess(BaseEntity baseEntity) {
                                    uprfid = true;
                                    mHandler.removeMessages(2);
                                }

                                @Override
                                public void onFail() {

                                }
                            });
                        }
                    } else {
                        Log.e("Kong", "RFID品类不匹配 ");
                    }
                }
            }

        }
    }

    private void getCleanOrder(String clearCode) {
        new BaseTask<CleanOrder>(this, RetroFactory.getJsonService().getCleanOrder(clearCode)).handleResponse(new BaseTask.ResponseListener<CleanOrder>() {

            @Override
            public void onSuccess(CleanOrder cleanOrder) {
                cleanBucket(clearCode, cleanOrder.getBucketCode());
            }

            @Override
            public void onFail() {

            }
        });
    }

    private void cleanBucket(String cleanCode, String bucketCode) {

        BucketType bucketBean = null;
        for (BucketType bucketType1 : bucketTypes) {
            if (bucketType1.getCode().equals(bucketCode)) {
                bucketBean = bucketType1;
                break;
            }
        }
        if (bucketBean != null) {

            Map<String, Object> par = new HashMap<>();
            par.put("code", cleanCode);
            DecimalFormat decimalFormat = new DecimalFormat("#0.00"); // 创建 DecimalFormat 对象并设置格式模式 "#0.00"
            String formattedNumber = decimalFormat.format((float) (bucketBean.getWeight()));
            par.put("quantity", formattedNumber);
            BucketType finalBucketBean = bucketBean;
            new BaseTask<BaseEntity>(this, RetroFactory.getJsonService().cleanBucket(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener() {
                @Override
                public void onSuccess(Object o) {
                    //开锁
                    Log.e("Kong", "执行开锁任务");
                    serialSendReceiveData.openLock(finalBucketBean.getNum());
                    mHandler.sendEmptyMessageDelayed(2, 60000);
                    uprfid = false;
                }


                @Override
                public void onFail() {

                }
            });
        }
//        }
    }

    public void comLoginHide(View view) {
        isTan = false;
        ttsService.interrupt();
        ConstraintLayout _mainTanView = findViewById(R.id.mainTanLogin);
        if (countDownTimer != null) countDownTimer.cancel();
        _mainTanView.setVisibility(View.GONE);
    }

    class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        //leftRight为横向间的距离 topBottom为纵向间距离
        private int leftRight;
        private int topBottom;

        public SpaceItemDecoration(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        public void setDecoration(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, android.view.View view, RecyclerView parent, RecyclerView.State state) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
            //竖直方向的
            if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
                //最后一项需要 bottom
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.bottom = topBottom;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.right = leftRight;
            } else {
                //最后一项需要right
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.right = leftRight;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.bottom = topBottom;
            }
        }


    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
//        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
//            View v = this.getWindow().getDecorView();
//            v.setSystemUiVisibility(View.GONE);
//        } else if (Build.VERSION.SDK_INT >= 19) {
//            //for new api versions.
//            View decorView = getWindow().getDecorView();
//            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
//            decorView.setSystemUiVisibility(uiOptions);
//        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            WindowInsetsController insetsController = getWindow().getInsetsController();
            if (insetsController != null) {
                // 隐藏导航栏
                insetsController.hide(WindowInsets.Type.navigationBars());
                // 显示导航栏
                // insetsController.show(WindowInsets.Type.navigationBars());

                // 如果你只想隐藏底部导航栏，可以使用下面的代码
                // insetsController.hide(WindowInsets.Type.navigationBar());

                // 请确保在适当的生命周期方法中进行这些调用，比如onResume()
            }
        }
    }

    public void updataYD() {
        Map<String, Object> par = new HashMap<>();
        par.put("code", RecoveryApplication.getInstance().getYhCode());
        List<JsonObject> appendixs = new ArrayList<>();

        for (int i = 0; i < Constant.imageUrl.size(); i++) {
            JsonObject item = new JsonObject();
            item.addProperty("type", "image");
            item.addProperty("originName", "截图");
            item.addProperty("isOut", "n");
            item.addProperty("path", Constant.imageUrl.get(i).toString());
            appendixs.add(item);
        }

        for (int i = 0; i < Constant.imageUrl1.size(); i++) {
            JsonObject item = new JsonObject();
            item.addProperty("type", "image");
            item.addProperty("originName", "截图");
            item.addProperty("isOut", "t");
            item.addProperty("path", Constant.imageUrl1.get(i).toString());
            appendixs.add(item);
        }

        par.put("appendixs", appendixs);

        //LogFileUtils.logToFile(gson.toJson(appendixs));
        Log.e("photo", "test()   " + gson.toJson(par) + " token " + RecoveryApplication.getInstance().getToken());
        OkHttpRequest okHttpRequest = new OkHttpRequest(getApplicationContext(), getSupportFragmentManager());
        okHttpRequest.sendPostRequestN("/sr-recycling/v1/01/recycle/inspect_appendix/create", gson.toJson(par), RecoveryApplication.getInstance().getToken(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.e("photo","test()  onFailure "+gson.toJson(par)+" token "+token);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("photo", "test()   chenggong");

            }
        });
    }

    CountDownTimer countDownTimer3 = new CountDownTimer(12000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            if (bucketTypes.size() > 0) {
                bucketTypes.get(0).setCompressStatus("00");
            }
            baseView.setList(bucketTypes);

        }
    };

}